<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="pdf名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入pdf名称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="乐器名称" prop="instrumentName">
                <el-input v-model="queryParams.instrumentName" placeholder="请输入乐器名称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="作曲家名称" prop="composerName">
                <el-input v-model="queryParams.composerName" placeholder="请输入作曲家名称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="合集名称" prop="collectionName">
                <el-input v-model="queryParams.collectionName" placeholder="请输入合集名称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="出版社名称" prop="publishName">
                <el-input v-model="queryParams.publishName" placeholder="请输入出版社名称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="出版信息名称" prop="publishInfoName">
                <el-input v-model="queryParams.publishInfoName" placeholder="请输入出版信息名称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" :disabled="multiple" plain icon="el-icon-plus" size="mini"
                    @click="handleRevert">恢复pdf</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['system:pdf:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['system:pdf:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleDelete" v-hasPermi="['system:pdf:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['system:pdf:export']">导出</el-button>
            </el-col> -->
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="pdfList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" align="center" prop="id" />
            <el-table-column label="pdf名称" align="center" prop="name" />
            <!-- 移除原有的pdf链接列 -->
            <el-table-column label="乐器" align="center" prop="instrumentName" />
            <el-table-column label="作曲家" align="center" prop="composerName" />
            <el-table-column label="合集" align="center" prop="collectionName" />
            <el-table-column label="出版社" align="center" prop="publishName" />
            <el-table-column label="出版信息" align="center" prop="publishInfoName" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-link"
                        @click="handleViewUrl(scope.row)">查看链接</el-button>
                    <el-button size="mini" type="text" icon="el-icon-refresh" @click="handleRevertSingle(scope.row)">恢复</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改pdf对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="pdf名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入pdf名称" />
                </el-form-item>
                <!-- <el-form-item label="pdf链接" prop="url">
            <el-input v-model="form.url" placeholder="请输入pdf链接" />
          </el-form-item> -->
                <el-form-item label="乐器" prop="instrumentId">
                    <el-autocomplete v-model="form.instrumentName" :fetch-suggestions="queryInstrumentList"
                        placeholder="请输入乐器名称" style="width: 100%" @select="handleInstrumentSelect"
                        @focus="handleInstrumentFocus" clearable>
                        <template slot-scope="{ item }">
                            <div>{{ item.name }}</div>
                        </template>
                    </el-autocomplete>
                </el-form-item>
                <el-form-item label="作曲家" prop="composerId">
                    <el-autocomplete v-model="form.composerName" :fetch-suggestions="queryComposerList"
                        placeholder="请输入作曲家名称" style="width: 100%" @select="handleComposerSelect"
                        @focus="handleComposerFocus" clearable>
                        <template slot-scope="{ item }">
                            <div>{{ item.name }}</div>
                        </template>
                    </el-autocomplete>
                </el-form-item>
                <el-form-item label="合集" prop="collectionId">
                    <el-autocomplete v-model="form.collectionName" :fetch-suggestions="queryCollectionList"
                        placeholder="请输入合集名称" style="width: 100%" @select="handleCollectionSelect"
                        @focus="handleCollectionFocus" clearable>
                        <template slot-scope="{ item }">
                            <div>{{ item.name }}</div>
                        </template>
                    </el-autocomplete>
                </el-form-item>
                <el-form-item label="出版社" prop="publishId">
                    <el-autocomplete v-model="form.publishName" :fetch-suggestions="queryPublishList"
                        placeholder="请输入出版社名称" style="width: 100%" @select="handlePublishSelect"
                        @focus="handlePublishFocus" clearable>
                        <template slot-scope="{ item }">
                            <div>{{ item.name }}</div>
                        </template>
                    </el-autocomplete>
                </el-form-item>
                <el-form-item label="出版社信息" prop="publishInfoId">
                    <el-autocomplete v-model="form.publishInfoName" :fetch-suggestions="queryInfoList"
                        placeholder="请输入出版社信息名称" style="width: 100%" @select="handleInfoSelect" @focus="handleInfoFocus"
                        :disabled="!form.publishId" clearable>
                        <template slot-scope="{ item }">
                            <div>{{ item.name }}</div>
                        </template>
                    </el-autocomplete>
                </el-form-item>
                <el-form-item label="文件id" prop="files">

                    <el-upload ref="upload" v-model="form.pdfFile" :limit="1" :on-change="handleFileChange"
                        :on-remove="handleFileRemove" :before-upload="beforePdfUpload" class="upload-demo" drag
                        action="#" :auto-upload="false" accept="application/pdf,.pdf">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">只能上传PDF文件</div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 查看链接弹窗 -->
        <el-dialog title="PDF链接" :visible.sync="urlDialogVisible" width="500px" append-to-body>
            <div class="url-container">
                <a :href="currentUrl" target="_blank" class="pdf-link">{{ currentUrl }}</a>
                <el-button type="primary" icon="el-icon-document-copy" @click="copyUrl">复制链接</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import {
    listPdf, getPdf, revertPdf, listCollectionSelect,
    listComposerSelect,
    listInstrumentSelect,
    listPublishSelect,
    listInfoSelect
} from "@/api/system/pdf"

export default {
    name: "Pdf",
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // pdf表格数据
            pdfList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 链接弹窗相关
            urlDialogVisible: false,
            currentUrl: "",
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                name: null,
                url: null,
                instrumentId: null,
                composerId: null,
                collectionId: null,
                publishId: null,
                publishInfoId: null,
                instrumentName: null,
                composerName: null,
                collectionName: null,
                publishName: null,
                publishInfoName: null,
                deleteFlag: '1'
            },
            // 表单参数
            form: {
                id: null,
                name: null,
                url: null,
                instrumentId: null,
                instrumentName: null,
                composerId: null,
                composerName: null,
                collectionId: null,
                collectionName: null,
                publishId: null,
                publishName: null,
                publishInfoId: null,
                publishInfoName: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                files: null
            },
            // 表单校验
            rules: {
            },
            // 下拉选项数据
            collectionOptions: [],
            composerOptions: [],
            instrumentOptions: [],
            publishOptions: [],
            infoOptions: []
        }
    },
    created() {
        this.getList()
    },
    // 添加activated钩子，当组件被激活时刷新列表
    activated() {
        this.getList()
    },
    methods: {
        /** 查询pdf列表 */
        getList() {
            this.loading = true
            listPdf(this.queryParams).then(response => {
                console.log(response.rows);
                this.pdfList = response.rows
                this.total = response.total
                this.loading = false
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                name: null,
                url: null,
                instrumentId: null,
                instrumentName: null,
                composerId: null,
                composerName: null,
                collectionId: null,
                collectionName: null,
                publishId: null,
                publishName: null,
                publishInfoId: null,
                publishInfoName: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                files: null
            }
            this.resetForm("form")
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        // 恢复pdf
        handleRevert() {
            const selectedIds = this.ids
            if (selectedIds.length === 0) {
                this.$modal.msgInfo("请选择要恢复的pdf")
                return
            }
            console.log("准备恢复PDF，选中的IDs:", selectedIds)
            this.$modal.confirm("确认要恢复选中的pdf吗?").then(function() {
                console.log("用户确认恢复，发送请求")
                return revertPdf(selectedIds)
            }).then(response => {
                console.log("恢复成功，响应:", response)
                this.$modal.msgSuccess("恢复成功")
                this.getList()
            }).catch(error => {
                // 用户取消操作不显示错误
                if (error === 'cancel') {
                    console.log("用户取消了操作")
                    return
                }
                console.error("恢复失败:", error)
                this.$modal.msgError("恢复失败: " + (error.message || '未知错误'))
            })
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm")
            // 确保名称字段也被重置
            this.queryParams.instrumentName = null;
            this.queryParams.composerName = null;
            this.queryParams.collectionName = null;
            this.queryParams.publishName = null;
            this.queryParams.publishInfoName = null;
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        // 恢复单个pdf
        handleRevertSingle(row) {
            const id = row.id
            console.log("准备恢复单个PDF，ID:", id)
            this.$modal.confirm("确认要恢复该pdf吗?").then(function() {
                console.log("用户确认恢复单个PDF，发送请求")
                return revertPdf([id])
            }).then(response => {
                console.log("恢复成功，响应:", response)
                this.$modal.msgSuccess("恢复成功")
                this.getList()
            }).catch(error => {
                // 用户取消操作不显示错误
                if (error === 'cancel') {
                    console.log("用户取消了操作")
                    return
                }
                console.error("恢复失败:", error)
                this.$modal.msgError("恢复失败: " + (error.message || '未知错误'))
            })
        },
        // 查看链接
        handleViewUrl(row) {
            this.currentUrl = row.url
            this.urlDialogVisible = true
        },
        // 复制链接
        copyUrl() {
            const input = document.createElement('input')
            input.value = this.currentUrl
            document.body.appendChild(input)
            input.select()
            document.execCommand('copy')
            document.body.removeChild(input)
            this.$message.success('链接已复制到剪贴板')
        },
        // 查询乐器列表
        queryInstrumentList(query, cb) {
            const params = {
                name: query
            }
            listInstrumentSelect(params).then(response => {
                cb(response.data)
            })
        },
        // 处理乐器选择
        handleInstrumentSelect(item) {
            this.form.instrumentId = item.id
            this.form.instrumentName = item.name
        },
        // 处理乐器输入框获取焦点
        handleInstrumentFocus() {
            if (!this.instrumentOptions.length) {
                this.queryInstrumentList('', result => {
                    this.instrumentOptions = result
                })
            }
        },
        // 查询作曲家列表
        queryComposerList(query, cb) {
            const params = {
                name: query
            }
            listComposerSelect(params).then(response => {
                cb(response.data)
            })
        },
        // 处理作曲家选择
        handleComposerSelect(item) {
            this.form.composerId = item.id
            this.form.composerName = item.name
        },
        // 处理作曲家输入框获取焦点
        handleComposerFocus() {
            if (!this.composerOptions.length) {
                this.queryComposerList('', result => {
                    this.composerOptions = result
                })
            }
        },
        // 查询合集列表
        queryCollectionList(query, cb) {
            const params = {
                name: query
            }
            listCollectionSelect(params).then(response => {
                cb(response.data)
            })
        },
        // 处理合集选择
        handleCollectionSelect(item) {
            this.form.collectionId = item.id
            this.form.collectionName = item.name
        },
        // 处理合集输入框获取焦点
        handleCollectionFocus() {
            if (!this.collectionOptions.length) {
                this.queryCollectionList('', result => {
                    this.collectionOptions = result
                })
            }
        },
        // 查询出版社列表
        queryPublishList(query, cb) {
            const params = {
                name: query
            }
            listPublishSelect(params).then(response => {
                cb(response.data)
            })
        },
        // 处理出版社选择
        handlePublishSelect(item) {
            this.form.publishId = item.id
            this.form.publishName = item.name
            // 清空出版信息
            this.form.publishInfoId = null
            this.form.publishInfoName = null
        },
        // 处理出版社输入框获取焦点
        handlePublishFocus() {
            if (!this.publishOptions.length) {
                this.queryPublishList('', result => {
                    this.publishOptions = result
                })
            }
        },
        // 查询出版信息列表
        queryInfoList(query, cb) {
            if (!this.form.publishId) {
                cb([])
                return
            }
            const params = {
                name: query,
                publishId: this.form.publishId
            }
            listInfoSelect(params).then(response => {
                cb(response.data)
            })
        },
        // 处理出版信息选择
        handleInfoSelect(item) {
            this.form.publishInfoId = item.id
            this.form.publishInfoName = item.name
        },
        // 处理出版信息输入框获取焦点
        handleInfoFocus() {
            if (!this.infoOptions.length && this.form.publishId) {
                this.queryInfoList('', result => {
                    this.infoOptions = result
                })
            }
        }
    }
}
</script>

<style scoped>
.url-container {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.pdf-link {
    word-break: break-all;
    margin-bottom: 15px;
    color: #409EFF;
    text-decoration: underline;
}

.url-container .el-button {
    margin-top: 10px;
}

.url-container .el-input {
    margin-right: 10px;
}
</style>